#!/usr/bin/env bash
set -e

BACKUP_DIR="$(cd "$(dirname "$0")" && pwd)"
BACKUP_FILE="$1"

if [ -z "$BACKUP_FILE" ]; then
  echo "用法: $0 <备份文件路径>"
  exit 1
fi

if [ ! -f "$BACKUP_FILE" ]; then
  echo "[ERROR] 找不到文件: $BACKUP_FILE"
  exit 1
fi

echo "[INFO] 停止 Jenkins 容器..."
docker-compose stop jenkins

echo "[INFO] 清空旧数据..."
docker run --rm -v jenkins_home:/data alpine sh -c "rm -rf /data/*"

echo "[INFO] 还原备份: $BACKUP_FILE"
docker run --rm -v jenkins_home:/data -v "$BACKUP_DIR":/backup alpine \
  sh -c "cd /data && tar xzf /backup/$(basename "$BACKUP_FILE")"

echo "[INFO] 还原完成。"

echo "[INFO] 启动 Jenkins 容器..."
docker-compose start jenkins